package com.riwon.im.common;

import com.riwon.im.pojo.User;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.Collectors;

/**
 * @author wpy
 * @date 2018/5/10 10:36
 */
@Deprecated
public class StaffContext {

    private Map<Integer,Queue<User>> staffMap;
    private Map<Integer,Queue<User>> staffMapCache;

    public StaffContext(@NotNull List<User> allStaffs){
        staffMapCache = new ConcurrentHashMap<>();

        Map<Integer, ConcurrentLinkedDeque<User>> staffMap = allStaffs.stream()
                .collect(Collectors.groupingBy(User::getShopId, Collectors.toCollection(ConcurrentLinkedDeque::new)));
        staffMap.forEach((integer, users) -> staffMapCache.put(integer,new ConcurrentLinkedDeque<User>()));
    }

    /**
     * 返回空代表没有客服或者shopid错误
     * @param appid
     * @return
     */
    public User getNextStaff(@NotNull Integer appid){
        Queue<User> userQueue = staffMap.get(appid);
        Queue<User> userQueueCache = staffMapCache.get(appid);

        if(userQueue == null){
            return null;
        }

        if(userQueue.isEmpty() && !userQueueCache.isEmpty()){
            Queue<User> temp = userQueue;
            userQueue = userQueueCache;
            userQueueCache = temp;
        }
        User user = userQueue.poll();
        userQueueCache.offer(user);
        return user;
    }

}
